package com.common.exception;

import com.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@ControllerAdvice
@Slf4j
@RestControllerAdvice(basePackages = "com.mall.product.controller")
public class ExceptionControllerAdvice {
    /**
     * 处理验证异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        List<FieldError> errors = e.getFieldErrors();
        Map<String,String> map = new HashMap<>();
        errors.forEach(c -> {
            map.put(c.getField(),c.getDefaultMessage());
        });
//        return R.error(400,"提交得数据不合法").put("data",map);
        return R.error(BizCodeEnums.VALID_EXCEPTION.getCode(),BizCodeEnums.VALID_EXCEPTION.getMsg()).put("data",map);
    }
    @ExceptionHandler(Throwable.class)
    public R handlerException(Throwable throwable){
        log.info("错误信息 -------->",throwable);
//        return R.error(400,"未知异常信息").put("data",throwable.getMessage());
        return R.error(BizCodeEnums.UNKNOW_EXCEPTION.getCode(), throwable.getMessage().contains("ception") ?
                        BizCodeEnums.UNKNOW_EXCEPTION.getMsg() : throwable.getMessage())
                .put("data",throwable.getMessage());
    }
}
